package com.itlong.cloud.commons.thread;

import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.push.message.WebSocketServerHandler;
import com.itlong.cloud.service.RedisService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <desc>
 *      用户token心跳缓存处理线程
 * </desc>
 *
 * @createDate 2019/09/25
 */
@Component
public class WebTokenPolling {
    private static final Logger LOG = LoggerFactory.getLogger(WebTokenPolling.class);

    private ExecutorService cachedThreadPool ; //线程池

    @Autowired
    RedisService redisService;

    /**
     * <desc>
     *      初始化
     * </desc>
     *
     * @author Jiaqi.X
     * @createDate 2018/04/10
     */
    @PostConstruct
    public void polling(){
        //初始化线程池
        cachedThreadPool = Executors.newFixedThreadPool(1);
        cachedThreadPool.execute(() -> {
            while (1 == 1) {
                try {
                    Map<String, Object> tokenMap = WebSocketServerHandler.tokenMap;
                    for(String userId : tokenMap.keySet()){
                        String tokenKey = "";
                        if((Integer)tokenMap.get(userId) == 1){
                            tokenKey = String.format("%s%s", RedisConstant.PROPERTY_USER_TOKEN_REDIS_CACHE_KEY, userId);
                        }else if ((Integer) tokenMap.get(userId) == 2){
                            tokenKey = String.format("%s%s", RedisConstant.OPERATE_REDIS_USER_TOKEN_CACHE_KEY, userId);
                        }
                        if(StringUtils.isBlank(redisService.get(tokenKey))){
                            String cacheKey ="";
                            //清空缓存
                            if((Integer)tokenMap.get(userId) == 1) {
                                //物业
                                cacheKey = String.format("%s%s", RedisConstant.PROPERTY_USER_REDIS_KEY, userId);
                            }else if ((Integer) tokenMap.get(userId) == 2){
                                //运营
                                cacheKey = String.format("%s%s", RedisConstant.OPERATE_REDIS_USER_KEY, userId);
                            }
                            redisService.del(cacheKey);
                        }
                    }
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    LOG.error("【心跳检测用户是否关闭页面处理失败】",e);
                }
            }
        });
    }
}